<template>
    <div>
        <el-breadcrumb
            separator-class="el-icon-arrow-right"
            class="breadcrumb-base"
            style="line-height: 30px;"
        >
            <el-breadcrumb-item>
                <i class="el-icon-collection"></i>
                字典管理
            </el-breadcrumb-item>
        </el-breadcrumb>

        <div class="main-container">
            <el-row>
                <el-input
                    v-model="inputKey"
                    placeholder="请输入关键字"
                    class="input-form"
                    size="mini"
                >
                </el-input>
                <el-button
                    @click="searchByName"
                    type="primary"
                    size="mini"
                >搜索</el-button>
                <el-button
                    @click="dictionaryDialogOpen(-1)"
                    type="primary"
                    size="mini"
                    style="float: right"
                >新增
                </el-button>
            </el-row>
            <el-row style="margin-top: 10px;">
                <base-table
                    ref="dictTable"
                    :data="dictionaries.data"
                    :header="dictionaries.header"
                    :pageInfo="dictionaries.pageInfo"
                    :selected="false"
                    @handleClick="dictTableButtonClick"
                    @pageJumpTo="dictTablePageJumpTo"
                    @sizeChange="dictTableSizeChange"
                >
                </base-table>
            </el-row>
        </div>
        <el-dialog
            :visible.sync="dictionaryDialog.visible"
            :title="dictionaryDialog.title"
            :close-on-click-modal="false"
            :modal-append-to-body="false"
            append-to-body
            width="30%"
        >
            <el-form
                ref="dictionaryForm"
                label-width="150px"
                :model="dictionaryForm"
                :rules="dictionaryFormRules"
            >
                <el-form-item
                    label="项目分类名称"
                    prop="name"
                    class="row-padding-bottom"
                >
                    <el-input
                        v-model="dictionaryForm.name"
                        placeholder="项目分类名称"
                        class="input-form"
                        size="mini"
                    ></el-input>
                </el-form-item>
                <el-form-item
                    label="项目分类代码"
                    prop="code"
                    class="row-padding-bottom"
                >
                    <el-input
                        v-model="dictionaryForm.code"
                        placeholder="项目分类代码"
                        class="input-form"
                        size="mini"
                        :disabled="dictionaryDialog.title === '编辑'"
                    ></el-input>
                </el-form-item>
                <el-form-item label="备注">
                    <el-input
                        v-model="dictionaryForm.remark"
                        placeholder="备注"
                        class="input-form"
                        size="mini"
                    ></el-input>
                </el-form-item>
            </el-form>
            <span
                slot="footer"
                class="dialog-footer"
                style="text-align: right;"
            >
                <el-button
                    @click="dictionaryDialogCommit"
                    type="primary"
                    size="mini"
                >提交</el-button>
                <el-button
                    @click="dictionaryDialog.visible = false"
                    size="mini"
                >关闭</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import BaseTable from '@templates/components/BaseTable';
import { itemsPerPage } from '@/client/libs/util';
import { vxRule } from '@/client/libs/validator';

export default {
    name: 'InstitutionDictionaries',

    components: {
        BaseTable,
    },

    data() {
        const checkName = (rule, value, callback) => {
            if (!value) {
                callback(new Error(' '));
                this.$message.warning('请填写项目分类名称');
            } else {
                callback();
            }
        };
        const checkCode = (rule, value, callback) => {
            if (!value) {
                callback(new Error(' '));
                this.$message.warning('请填写项目分类名称');
            } else {
                callback();
            }
        };

        return {
            inputKey: '',
            searchKey: '',

            // 字典数据
            dictionaries: {
                data: [],
                header: [
                    {
                        prop: 'name',
                        label: '操作',
                        fixed: true,
                        width: '210',
                        isRender: true,
                        render: (h, params) => {
                            const _vm = this;
                            const props = {
                                type: 'text',
                                disabled: false,
                                size: 'small',
                                circle: 'circle',
                            };
                            const staticStyle = {
                                margin: '0 0px',
                            };
                            return h('div', [
                                h('span', [
                                    h(
                                        'el-button',
                                        {
                                            props: props,
                                            on: {
                                                click: function ($event) {
                                                    return _vm.dictTableEdit(
                                                        params.row
                                                    );
                                                },
                                            },
                                            staticStyle: { ...staticStyle },
                                        },
                                        '编辑'
                                    ),
                                ]),
                                h('span', [
                                    h(
                                        'el-button',
                                        {
                                            props: props,
                                            on: {
                                                click: function ($event) {
                                                    return _vm.dictTableMaintain(
                                                        params.row
                                                    );
                                                },
                                            },
                                            staticStyle: { ...staticStyle },
                                        },
                                        '字典信息维护'
                                    ),
                                ]),

                                h('span', [
                                    h(
                                        'el-button',
                                        {
                                            props: {
                                                ...props,
                                                disabled:
                                                    !params.row
                                                        .isAbledUpdatedType,
                                            },
                                            on: {
                                                click: function ($event) {
                                                    return _vm.dictTableDelete(
                                                        params.row
                                                    );
                                                },
                                            },
                                            staticStyle: {
                                                ...staticStyle,
                                                color: params.row
                                                    .isAbledUpdatedType
                                                    ? 'red'
                                                    : '',
                                            },
                                        },
                                        '删除'
                                    ),
                                ]),
                            ]);
                        },
                    },
                    {
                        label: '项目分类名称',
                        prop: 'name',
                        width: '240',
                    },
                    {
                        label: '项目分类代码',
                        prop: 'code',
                        width: '240',
                    },
                    {
                        label: '备注',
                        prop: 'remark',
                    },
                ],
                operation: [
                    {
                        label: '编辑',
                        functionKey: 'dictTableEdit',
                    },
                    {
                        label: '字典信息维护',
                        functionKey: 'dictTableMaintain',
                    },
                    {
                        label: '删除',
                        color: 'red',
                        functionKey: 'dictTableDelete',
                    },
                ],
                // 分页信息
                pageInfo: {
                    size: itemsPerPage.get(),
                    page: 1,
                    total: 0,
                },
            },
            dictionaryDialog: {
                visible: false,
                commitMethod: '',
                title: '',
            },
            dictionaryForm: {
                id: 0,
                name: '',
                code: '',
                remark: '',
            },
            dictionaryFormRules: {
                name: [
                    vxRule(true, null, 'blur', '请填写项目分类名称'),
                    vxRule(
                        true,
                        'length',
                        'blur',
                        '项目分类名称填写请不要超过255个字符',
                        null,
                        255
                    ),
                ],
                code: [
                    vxRule(true, null, 'blur', '请填写项目分类代码'),
                    vxRule(
                        true,
                        'length',
                        'blur',
                        '项目分类代码填写请不要超过255个字符',
                        null,
                        255
                    ),
                ],
            },
        };
    },
    mounted() {
        this.requestDictionary();
    },
    methods: {
        // 关键字搜素
        searchByName() {
            this.searchKey = this.inputKey;
            this.dictionaries.pageInfo.page = 1;
            this.requestDictionary();
        },
        // 表格 - 按钮点击
        dictTableButtonClick(functionKey, row) {
            this[functionKey](row);
        },
        // 表格 - 编辑
        dictTableEdit(row) {
            this.dictionaryDialogOpen(row.index);
        },
        // 表格 - 字典信息维护
        dictTableMaintain(row) {
            this.$router.push(`${this.$route.path}/info/${row.code}`);
        },
        // 表格 - 删除
        dictTableDelete(row) {
            this.$confirm('删除该字典类型, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            })
                .then(async () => {
                    try {
                        await this.$axios({
                            // 详见 axios 请求配置项
                            method: 'DELETE',
                            url: `/PROXY-Remote/dictionary-type/${row.id}`,
                        }).then((res) => {
                            // 请求失败
                            if (res.data.code !== 200) {
                                throw new Error(res.data);
                            }

                            // 请求成功
                            // const result = res.data.data;
                            this.$message.success('删除成功!');
                            if (this.dictionaries.data.length === 1) {
                                if (this.dictionaries.pageInfo.page > 1) {
                                    this.dictionaries.pageInfo.page -= 1;
                                }
                            }
                            this.requestDictionary();
                        });
                    } catch (e) {
                        // 跳出
                    }
                })
                .catch(() => {});
        },
        // 分页跳转
        dictTablePageJumpTo(val) {
            this.dictionaries.pageInfo.page = val;
            this.requestDictionary();
        },
        // 每页显示数量改变
        dictTableSizeChange(val) {
            this.dictionaries.pageInfo.size = val;
            this.dictionaries.pageInfo.page = 1;
            this.requestDictionary();
        },

        // 请求字典数据
        async requestDictionary() {
            try {
                await this.$axios({
                    // 详见 axios 请求配置项
                    method: 'GET',
                    url: '/PROXY-Remote/dictionary-type',
                    params: {
                        name: this.searchKey,
                        size: this.dictionaries.pageInfo.size,
                        page: this.dictionaries.pageInfo.page - 1,
                    },
                }).then((res) => {
                    // 请求失败
                    if (res.data.code !== 200) {
                        throw new Error(res.data);
                    }

                    // 请求成功
                    const result = res.data;
                    // 分页信息
                    this.dictionaries.pageInfo = {
                        total: result.pageInfo.total,
                        page: result.pageInfo.page + 1,
                        size: result.pageInfo.size,
                    };
                    // 查询结果数据
                    this.dictionaries.data = [];
                    result.data.forEach((t) => {
                        this.dictionaries.data.push({
                            index: this.dictionaries.data.length,
                            id: t.id,
                            name: t.name,
                            code: t.code,
                            remark: t.remark,
                            isAbledUpdatedType: t.isAbledUpdatedType === 1,
                        });
                    });
                });
            } catch (e) {
                // 跳出
            }
        },
        // 对话框 - 打开
        dictionaryDialogOpen(index) {
            // 初始化
            this.dictionaryForm = {
                id: 0,
                name: '',
                code: '',
                remark: '',
            };

            if (index < 0) {
                this.dictionaryDialog.title = '新增';
                this.dictionaryDialog.commitMethod = 'POST';
                // 新增字典不带 id 字段
                delete this.dictionaryForm.id;
            } else {
                this.dictionaryDialog.title = '编辑';
                this.dictionaryDialog.commitMethod = 'PUT';
                // 赋值
                Object.keys(this.dictionaryForm).forEach((key) => {
                    this.dictionaryForm[key] =
                        this.dictionaries.data[index][key];
                });
            }

            this.dictionaryDialog.visible = true;
        },
        // 对话框 - 提交
        dictionaryDialogCommit() {
            this.$refs.dictionaryForm.validate(async (valid) => {
                if (valid) {
                    try {
                        await this.$axios({
                            // 详见 axios 请求配置项
                            method: this.dictionaryDialog.commitMethod,
                            url: '/PROXY-Remote/dictionary-type',
                            data: this.dictionaryForm,
                        }).then((res) => {
                            // 请求失败
                            if (res.data.code !== 200) {
                                this.$message.error({
                                    message: res.data.message,
                                });
                                return;
                            }

                            // 请求成功
                            this.$message.success(
                                `${this.dictionaryDialog.title}成功`
                            );

                            this.dictionaryDialog.visible = false;
                            this.requestDictionary();
                        });
                    } catch (e) {
                        // 跳出
                    }
                }
            });
        },
    },
};
</script>

<style scoped>
.row-padding-bottom {
    padding-bottom: 10px;
}
</style>
